﻿/*globals _comma_separated_list_of_variables_*/
//## LEAGAL
/*
#region - Legal -

Copyright © 2011, Tateeda Media Network
All rights reserved. http://tateeda.com

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

- Neither the name of the Tateeda Media Network, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior written
permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

#endregion - Legal -

*/
//#end
//## Variables
var DEFAULT_TOP_CATEGORY = 1;
var DEFAULT_PSYCOTROPIC_CATEGORY = 1;
var DEFAULT_NON_PSYCOTROPIC_CATEGORY = 2;
var DEFAULT_NON_PSYCHOTROPIC_CLASS = 7;
var arNonPsychoDrugs = new Array();
//#end

$(document).ready(function () {
    var date;

    var prescriptionStart = $("#prescriptionStart").datepicker({
        defaultDate: "-1w",
        changeMonth: true,
        numberOfMonths: 3,
        onSelect: function (selectedDate) {
            var option = this.id == "prescriptionStart" ? "minDate" : "maxDate", instance = $(this).data("datepicker");
            date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
            prescriptionStart.not(this).datepicker("option", option, date);
        }
    });

    var prescriptionEnd = $("#prescriptionEnd").datepicker({
        defaultDate: "-1w",
        changeMonth: true,
        numberOfMonths: 3,
        onSelect: function (selectedDate) {
            var option = this.id == "prescriptionEnd" ? "minDate" : "maxDate", instance = $(this).data("datepicker");
            date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
            prescriptionEnd.not(this).datepicker("option", option, date);
        }
    });

    var nonPsychoStartDate = $("#nonPsychoStartDate").datepicker({
        defaultDate: "-3m",
        changeMonth: true,
        numberOfMonths: 3,
        onSelect: function (selectedDate) {
            var option = this.id == "nonPsychoStartDate" ? "minDate" : "maxDate", instance = $(this).data("datepicker");
            date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
            nonPsychoStartDate.not(this).datepicker("option", option, date);
        }
    });

    var nonPsychoEndDate = $("#nonPsychoEndDate").datepicker({
        defaultDate: "1w",
        changeMonth: true,
        numberOfMonths: 3,
        onSelect: function (selectedDate) {
            var option = this.id == "nonPsychoEndDate" ? "minDate" : "maxDate", instance = $(this).data("datepicker");
            date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
            nonPsychoEndDate.not(this).datepicker("option", option, date);
        }
    });

    $.ajax({
        type: "POST",
        url: "/Study/GetPrescriptionDrugCategory",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            LoadPrescriptionsCategory(data);
        },
        error: function (e) {
            alert(e.responseText.substring(11, e.responseText.indexOf("StackTrace") - 2));
        }
    });

    //NON PSYCHO Drugs:
    GetNonPsychoDrugName(DEFAULT_NON_PSYCHOTROPIC_CLASS);

    $(".currentMedstopDateSpan").hide();
    $(".currentMedChangeDoseSpan").hide();
});
/********************************************************* Tobacco/Alcohol/Caffeine/Supplements *******************************************************/

function AddTobacco() {
    var kind = "Tobacco";
    var name = " ";
    var frequencyId = 17; //frequencyId per day.
    // $("#tobaccoName").val();
    var dose = $("#tobaccoDose").val();
    var unit = "Per Day";
    var comment = $("#tobaccoComments").val();
    if (IsNumeric(dose)) {
        AddSubstance(kind, name, dose, unit, comment, frequencyId);
        $("#tobaccoDose").val('');
        $("#tobaccoComments").val('');
        $("#tobaccoResult").html("<b>Value was added</b>");
        $("#tobaccoDose").css("background-color", "white");
    } else {
        alert("Dose must be a numeric value");
        $("#tobaccoResult").html('');
        $("#tobaccoDose").css("background-color", "yellow").val('');
    }
}

function AddAlcohol() {
    var kind = "Alcohol";
    var name = " ";
    var frequencyId = 18; //frequencyId weekly.
    // $("#alcoholName").val();
    var dose = $("#alcoholDose").val();
    var unit = "Per Week";
    var comment = $("#alcoholComments").val();
    if (IsNumeric(dose)) {
        AddSubstance(kind, name, dose, unit, comment, frequencyId);
        $("#alcoholDose").val('');
        $("#alcoholComments").val('');
        $("#alcoholResult").html("<b>Value was added</b>");
        $("#alcoholDose").css("background-color", "white");
    } else {
        alert("Dose must be a numeric value");
        $("#alcoholResult").html('');
        $("#alcoholDose").css("background-color", "yellow").val('');
    }
}

function AddRecDrug() {
    var kind = $("#RecDrugCategroy option:selected").val();
    var name = $("#substanceName").val();
    var dose = $("#substanceDose").val();
    var unit = "Per Week";
    var comment = $("#substanceComments").val();
    var frequencyId = 18; //frequencyId per week.

    if (IsNumeric(dose) && name.length > 0 && (kind.length > 0 && kind.indexOf("Select") < 0)) {
        AddSubstance(kind, name, dose, unit, comment, frequencyId);
        $("#substanceDose").val('');
        $("#substanceName").val('');
        $("#substanceComments").val('');
        $("#ordResult").html("<b>Value was added</b>");

        $("#substanceDose").css("background-color", "white");
        $("#RecDrugCategroy").css("background-color", "white");
        $("#substanceName").css("background-color", "white");
        $("#RecDrugCategroy").val('');
    } else {
        $("#ordResult").html('');
        if (!IsNumeric(dose))
            $("#substanceDose").css("background-color", "yellow").val('');
        if (kind.indexOf('Select') > 0 || kind.length == 0)
            $("#RecDrugCategroy").css("background-color", "yellow");
        if (name.length <= 0)
            $("#substanceName").css("background-color", "yellow");
    }
}

function AddCaffeine() {
    var kind = "Caffeine";
    var name = " ";
    var frequencyId = 17; //frequencyId per day.
    // $("#caffeineName").val();
    var dose = $("#caffeineDose").val();
    var unit = "Per Day";
    var comment = $("#caffeineComments").val();
    if (IsNumeric(dose)) {
        AddSubstance(kind, name, dose, unit, comment, frequencyId);
        $("#caffeineDose").val('');
        $("#caffeineComments").val('');
        $("#caffeineResult").html("<b>Value was added</b>");
        $("#caffeineDose").css("background-color", "white");
    } else {
        alert("Dose must be a numeric value");
        $("#caffeineDose").css("background-color", "yellow").val('');
        $("#caffeineResult").html('');
    }
}

function AddSupplements() {
    var kind = "Supplements";
    var name = $("#supplementsName").val();
    var dose = $("#supplementsDose").val();
    var unit = "Per Week";
    var comment = $("#supplementsComments").val();
    var frequencyId = 17; //frequencyId per day.

    if (IsNumeric(dose)) {
        AddSubstance(kind, name, dose, unit, comment, frequencyId);
        $("#supplementsDose").val('');
        $("#supplementsName").val('');
        $("#supplementsComments").val('');
        $("#supplementsResult").html("<b>Value was added</b>");
        $("#supplementsName").css("background-color", "white");
        $("#supplementsDose").css("background-color", "white");
    } else {
        $("#supplementsResult").html('');
        if (!IsNumeric(dose)) {
            alert("Dose must be a numeric value");
            $("#supplementsDose").css("background-color", "yellow").val('');
        }
        if (name.length <= 0)
            $("#supplementsName").css("background-color", "yellow");
    }
}

/********************************************************* Substance *******************************************************/

function AddSubstance(kind, name, dose, unit, comment, frequencyId) {
    var sid = $("#subjectId").val();
    var aid = $("#appointmentId").val();
    //int subjectId, int appointementId, string kind, string name, int dose, string unit, string comment)
    $.ajax({
        type: "POST",
        url: "/Study/AddSubstance",
        data: "{'subjectId':'" + sid + "','appointmentId':'" + aid + "','kind':'" + kind + "','name':'" + name + "','dose':'" + dose + "','unit':'" + unit + "','comment':'" + comment + "','frequencyId':'" + frequencyId + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            LoadVisitSubstanceSummary(data);
        },
        error: function (e) {
            alert("error " + e.responseText);
        }
    });
}

function LoadVisitSubstanceSummary(data) {
    var display = $("#visitSubstaceSummary");
    var htmlStr = "";

    for (var i = 0; i < data.length; i++) {
        htmlStr += "<div class='clearfix fullDiv'><span class='leftSubstance'>" + data[i].TypeName + " " + data[i].Name + " <b>" + data[i].Dose + "</b> Units " + data[i].Unit + " <i>" + data[i].Comments + "</i></span>";
        htmlStr += "<span class='rightSubstance'><input type='button' value='Delete' class='buttonGlobalShort deleteSmall' onclick=\"DeleteSubjectsSubstance('" + data[i].RecreationalDrugOrSubstanceId + "'); window.location=window.location;\"></span></div><br/>";
    }

    display.html(htmlStr);
}

/********************************************************* Prescription *******************************************************/

function LoadPrescriptionsCategory(data) {
    /*Do not use for now.. call only one Category
    $.each(data, function (id, obj) {
    if (obj.Name != "Over Counter Drugs") {
    $('#prescriptionCategory').
    append($("<option></option>").
    attr("value", obj.Id).
    text(obj.Name));
    }
    });

    $('#prescriptionCategory').change(function () {
    GetPrescriptionClass($("#prescriptionCategory option:selected").val());
    });
    */

    GetPrescriptionClass(DEFAULT_TOP_CATEGORY);
}

function GetPrescriptionClass(id) {
    $('#prescriptionClass').find('option').remove().end().append('<option>--Select--</option>');
    $('#prescriptionName').find('option').remove().end().append('<option>--Select--</option>');

    if (id > 0) {
        $.ajax({
            type: "POST",
            url: "/Study/GetPrescriptionDrugClass",
            data: "{'categoryId':'+" + id + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                LoadPrescriptionClass(data);
            },
            error: function (e) {
                alert("error " + e.responseText);
            }
        });
    }
}

function LoadPrescriptionClass(data) {
    $.each(data, function (id, obj) {
        $('#prescriptionClass').append($("<option></option>").val(obj.DrugClassId).html(obj.Name));
    });

    $('#prescriptionClass').change(function () {
        GetPrescriptionName($("#prescriptionClass option:selected").val());
    });
}

function GetPrescriptionName(id) {
    if (id > 0) {
        $.ajax({
            type: "POST",
            url: "/Study/GetPrescriptionDrugNames",
            data: "{'classId':'+" + id + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                LoadPrescriptionName(data);
            },
            error: function (e) {
                alert("error " + e.responseText);
            }
        });
    } else {
        $('#prescriptionName').find('option').remove().end().append('<option>--Select--</option>');
    }
}

function LoadPrescriptionName(data) {
    $('#prescriptionName').find('option').remove().end().append('<option>--Select--</option>');

    $.each(data, function (id, obj) {
        $('#prescriptionName').append($("<option></option>").val(obj.DrugId).html(obj.Name));
    });
}

function GetNonPsychoDrugName(id) {
    /*
    if (id > 0) {
    $.ajax({
    type: "POST",
    url: "/Study/GetPrescriptionDrugName",
    data: "{'classId':'+" + id + "'}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
    LoadNonPsychoDrugName(data);
    },
    error: function (e) {
    alert("error " + e.responseText);
    }
    });
    } else {
    $('#nonPsychoDrugName')
    .find('option')
    .remove()
    .end()
    .append('<option>--Select--</option>');
    }
    */

    //LoadNonPsychoDrugName(arNonPsychoDrugs);
}

function LoadNonPsychoDrugName(data) {
    if (data != undefined && data != "") {
        $('#nonPsychoDrugName').find('option').remove().end().append('<option>--Select--</option>');

        var arData = data.split("|");

        $.each(arData, function (index, obj) {
            var vals = obj.split("^");
            $('#nonPsychoDrugName').append($("<option></option>").attr("value", vals[0]).text(vals[1]));
        });

        arNonPsychoDrugs = data;
    }
}

function AddNonPsychoDrug() {
    var appointmentId = $("#appointmentId").val();
    var subjectId = $("#subjectId").val();
    var frequencyId = $("#nonPsycoFrequency").val();

    var categoryId = DEFAULT_NON_PSYCOTROPIC_CATEGORY;
    var classId = DEFAULT_NON_PSYCHOTROPIC_CLASS;

    var drugNameId = $("#editableComboboxInputText").val();
    //$("#editableComboboxnonPsychoDrugName option:selected").val();
    var dose = $("#nonPsychoDose").val();
    var doseUnit = $("#nonPsychoDrugUnit option:selected").val();
    var startDate = $("#nonPsychoStartDate").val();
    var endDate = $("#nonPsychoEndDate").val();
    var isBeforeStudy = false;
    var comments = $("#nonPsychoComment").val();

    var isValidDates = ValidateDates(startDate, endDate);

    if (ValidateMedsFields("NonPsychoDrugsRoot") == true && isValidDates == true) {
        $.ajax({
            type: "POST",
            url: "/Study/AddSubjectNonSychotropicDrug",
            data: "{'subjectId':'" + subjectId + "','appointmentId':'" + appointmentId +
                "','classId':'" + classId + "','drugNameId':'" + drugNameId + "','dose':'" + dose + "','doseUnit':'" + doseUnit +
                "','startDate':'" + startDate + "','endDate':'" + endDate + "','isBeforeStudy':'" + isBeforeStudy +
                "','comments':'" + comments + "','frequencyId':'" + frequencyId + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                LoadAppointmentMedication(data);
            },
            error: function (e) {
                alert("error " + e.responseText);
            }
        });

        $("#nonPsychoDrugName").val('');
        //Reset to -Select-
        $("#nonPsychoDose").val('');
        $("#nonPsychoDrugUnit").val('');
        $("#nonPsychoStartDate").val('');
        $("#nonPsychoEndDate").val('');
        $("#nonPsycoFrequency").val('');
        $("#editableComboboxInputText").val('');
        $("#_NonPsycoDrugController").val('');
        $("#nonPsychoComment").val('');
    }
}

function AddPrescription() {
    var appointmentId = $("#appointmentId").val();
    var subjectId = $("#subjectId").val();
    var categoryId = DEFAULT_PSYCOTROPIC_CATEGORY;
    var classId = $("#prescriptionClass option:selected").val();
    var drugNameId = $("#prescriptionName option:selected").val();
    var dose = $("#prescriptionDose").val();
    var doseUnit = $("#prescriptionDrugUnit option:selected").val();
    var startDate = $("#prescriptionStart").val();
    var endDate = $("#prescriptionEnd").val();
    var isBeforeStudy = false;
    var comments = $("#prescriptionComment").val();
    var frequencyId = $("#psycoFrequency").val();

    var isValidDates = ValidateDates(startDate, endDate);

    if (ValidateMedsFields("PsychoDrugsRoot") == true && isValidDates == true) {
        $.ajax({
            type: "POST",
            url: "/Study/AddPrescriptionDrug",
            data: "{'subjectId':'" + subjectId + "','appointmentId':'" + appointmentId + "','classId':'" + classId +
                "','drugNameId':'" + drugNameId + "','dose':'" + dose + "','doseUnit':'" + doseUnit +
                "','startDate':'" + startDate + "','endDate':'" + endDate + "','isBeforeStudy':'" + isBeforeStudy +
                "','comments':'" + comments + "','frequencyId':'" + frequencyId + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                LoadAppointmentMedication(data);
            },
            error: function (e) {
                alert("error " + e.responseText);
            }
        });

        $("#prescriptionCategory option:first").attr("selected", "selected");
        $('#prescriptionName').find('option').remove().end().append('<option>--Select--</option>');
        $('#prescriptionClass').find('option').remove().end().append('<option>--Select--</option>');
        $("#prescriptionDose").val('');
        $("#prescriptionComment").val('');
        $("#prescriptionEnd").val('');
        $("#prescriptionStart").val('');
        $("#psycoFrequency").val('');
        $("#prescriptionDrugUnit").val('');

        GetPrescriptionClass(DEFAULT_TOP_CATEGORY);
    }
}

function ValidateMedsFields(parentId) {
    var checked = true;
    $("#" + parentId + " .required").each(function () {
        var value = $(this).val();
        if (!value || value.indexOf("--") >= 0) {
            $(this).parent().css("background-color", "yellow");
            $(this).focus();
            checked = false;
            return checked;
        } else {
            $(this).parent().css("background-color", "white");
        }
        return checked;
    });

    return checked;
}

function LoadAppointmentMedication(data) {
    var htmlStrPsyco = "";
    var htmlStrNonPsyco = "";
    var htmlStr = "";
    var today = new Date();

    for (var i = 0; i < data.length; i++) {
        var subjectDrugId = data[i].SubjectDrugId;
        var startDate = new Date(data[i].StartDate.substring(6, 19) * 1);

        var isCurrent = "<b>Stopped</b>";
        if (data[i].IsCurrent)
            isCurrent = "<b>Current</b>";
        else {
            var stopDate = new Date(data[i].EndDate.substring(6, 19) * 1);
            isCurrent = "<b>Stopped</b> on: " + ((stopDate.getMonth() + 1) + "/" + stopDate.getDate() + "/" + stopDate.getFullYear());
        }

        htmlStr = "";

        if (isCurrent == "<b>Current</b>") {
            htmlStr += "<span class='currentMedChangeDoseSpan' id='currentMedChangeDoseSpan_" + subjectDrugId + "'>&nbsp;";
            htmlStr += "<span class='Title'>Dose:&nbsp;</span><input type='text' id='currentMedChangeDose_" + subjectDrugId + "' class='textBoxShort20Global' value='" + data[i].Dosage + "'/>&nbsp;";
            htmlStr += "<span class='Title'>Date:&nbsp;</span><input type='text' id='currentMedChangeDate_" + subjectDrugId + "' class='textBoxForDatesGlobal' value='";
            htmlStr += (today.getMonth() + 1) + "/" + today.getDate() + "/" + today.getFullYear() + "'/>&nbsp;";
            htmlStr += "<input type='button' value='Update' class='ButtonGlobalShort editSmall' onclick=UpdateChangeDoseDrug('" + subjectDrugId + "');>&nbsp;";
            htmlStr += "</span>&nbsp;";

            htmlStr += "<input type='button' value='Stop' class='buttonGlobalShort stopSmall' onclick=StopDrug('" + subjectDrugId + "');>&nbsp;";
            htmlStr += "<input type='button' value='Change' class='buttonGlobalShort editSmall' onclick=ChangeDoseDrug('" + subjectDrugId + "');>";
            htmlStr += "<span class='currentMedstopDateSpan' id='currentMedstopDateSpan_" + subjectDrugId + "'><span class='Title'>&nbsp;Date:&nbsp;</span>";
            htmlStr += "<input type='text' id='currentMedstopDate_" + subjectDrugId + "' class='TextBoxForDatesGlobal' value='";
            htmlStr += (today.getMonth() + 1) + "/" + today.getDate() + "/" + today.getFullYear() + "'/>&nbsp;";
            htmlStr += "<input type='button' value='Update' class='ButtonGlobalShort editSmall' onclick=UpdateStopDrug('" + subjectDrugId + "');>&nbsp;";
            htmlStr += "</span>&nbsp;";
        }

        htmlStr += "<b><i>" + data[i].Name + "</i></b> <strong>" + data[i].Dosage + "</strong> " + data[i].DosageType;
        htmlStr += "&nbsp; Comment: " + data[i].Comments + "&nbsp;";
        htmlStr += " Started on: " + (startDate.getMonth() + 1) + "/" + startDate.getDate() + "/" + startDate.getFullYear() + " - " + isCurrent;
        htmlStr += "&nbsp;<input type='button' value='Delete' class='buttonGlobalShort deleteSmall' onclick=DeleteSubjectsDrug('" + subjectDrugId + "');>&nbsp;";
        htmlStr += "<input readonly='readonly' style='width:40px;' class='historyIcon' onclick=\"GetMedicationChangeHistory('";
        htmlStr += subjectDrugId + "');\" />&nbsp;<span id='history_" + subjectDrugId + "' class='history'  onclick=\"HideHistory('" + subjectDrugId + "');\"></span>&nbsp;<br/>";
        htmlStr += "<br/>";

        if (data[i].IsSychotropic) {
            htmlStrPsyco += htmlStr;
        } else {
            htmlStrNonPsyco += htmlStr;
        }
    }

    $("#currentPsycoSummary").html(htmlStrPsyco);
    $("#currentNonPsycoSummary").html(htmlStrNonPsyco);
    $(".currentMedstopDateSpan").hide();
    $(".currentMedChangeDoseSpan").hide();
}

function StopDrug(medId) {
    $(".currentMedChangeDoseSpan").hide();
    $("#currentMedstopDateSpan_" + medId).show("slow");
}

function UpdateStopDrug(id) {
    var date = $("#currentMedstopDate_" + id).val();
    $.ajax({
        type: "POST",
        url: "/Study/StopPrescriptionDrug",
        data: "{'subjectDrugId':'" + id + "','stopDate':'" + date + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            LoadAppointmentMedication(data);
        },
        error: function (e) {
            alert("error " + e.responseText);
        }
    });
}

function ChangeDoseDrug(id) {
    $(".currentMedstopDateSpan").hide();
    $("#currentMedChangeDoseSpan_" + id).show("slow");
}

function UpdateChangeDoseDrug(id) {
    var dose = $("#currentMedChangeDose_" + id).val();
    var changeDate = $("#currentMedChangeDate_" + id).val();

    $.ajax({
        type: "POST",
        url: "/Study/ChangePrescriptionDrugDose",
        data: "{'subjectDrugId':'" + id + "','dose':'" + dose + "','changeDate':'" + changeDate + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            LoadAppointmentMedication(data);
        },
        error: function (e) {
            alert(e.responseText.substring(11, e.responseText.indexOf("StackTrace") - 2));
        }
    });
}

/************************************* Medication History *******************************************************/

function AddMedicationHistory() {
    var appointmentId = $("#appointmentId").val();
    var subjectId = $("#subjectId").val();
    var categoryId = DEFAULT_PSYCOTROPIC_CATEGORY;
    var classId = $("#prescriptionClass option:selected").val();
    var drugNameId = $("#prescriptionName option:selected").val();
    var doseUnit = $("#prescriptionDrugUnit option:selected").val();
    var startDate = $("#prescriptionStart").val();
    var endDate = $("#prescriptionEnd").val();
    var comments = $("#medHistoryComments").val();
    var maxDose = $("#maxDose").val();
    var multipleTrialId = $("#multipleTrialsList option:selected").val();
    var durationUsedWeeks = -1;
    var reasonStoppedId = $("#reasonStopped option:selected").val();
    var responseTypeId = $("#responseType option:selected").val();
    var treatmentInducedId = $("#treatmentInduced option:selected").val();

    if (VadilateHistoryMedsFields()) {
        var isBeforeStudy = true;

        if (subjectId && startDate && drugNameId) {
            $.ajax({
                type: "POST",
                url: "/Study/AddMedicationHistory",
                data: "{'subjectId':'" + subjectId + "','appointmentId':'" + appointmentId +
                        "','categoryId':'" + categoryId + "','classId':'" + classId +
                        "','drugNameId':'" + drugNameId + "','dose':'" + maxDose +
                        "','doseUnit':'" + doseUnit + "','startDate':'" + startDate +
                        "','endDate':'" + endDate + "','isBeforeStudy':'" + isBeforeStudy +
                        "','multipleTrialId':'" + multipleTrialId +
                        "','durationUsedWeeks':'" + durationUsedWeeks +
                        "','reasonStoppedId':'" + reasonStoppedId +
                        "','responseTypeId':'" + responseTypeId +
                        "','treatmentInducedId':'" + treatmentInducedId +
                        "','comments':'" + comments + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    LoadMedicationHistory(data);
                },
                error: function (e) {
                    alert(e.responseText.substring(11, e.responseText.indexOf("StackTrace") - 2));
                }
            });

            $('#prescriptionCategory option:first').attr("selected", "selected");
            $("#treatmentInduced option:first").attr("selected", "selected");
            $('#prescriptionName').find('option').remove().end().append('<option>--Select--</option>');
            $('#prescriptionClass').find('option').remove().end().append('<option>--Select--</option>');
            $("#maxDose").val('');
            $("#medHistoryComments").val('');
            $("#prescriptionEnd").val('');
            $("#prescriptionStart").val('');
            $('#multipleTrialsList').val('');
            $('#reasonStopped').val('');
            $('#responseType').val('');

            GetPrescriptionClass(DEFAULT_TOP_CATEGORY);
        }
    }
}

function VadilateHistoryMedsFields() {
    var classId = $("#prescriptionClass option:selected").val();
    var drugNameId = $("#prescriptionName option:selected").val();
    var doseUnit = $("#prescriptionDrugUnit option:selected").val();
    var startDate = $("#prescriptionStart").val();
    var maxDose = $("#maxDose").val();
    var multipleTrialId = $("#multipleTrialsList option:selected").val();
    var reasonStoppedId = $("#reasonStopped option:selected").val();
    var responseTypeId = $("#responseType option:selected").val();
    var treatmentInducedId = $("#treatmentInduced option:selected").val();
    var endDate = $("#prescriptionEnd").val();

    if (classId == "--Select--") {
        $("#prescriptionClass").parent().css("background-color", "yellow");
        return false;
    } else {
        $("#prescriptionClass").parent().css("background-color", "white");
    }

    if (drugNameId == "--Select--") {
        $("#prescriptionName").parent().css("background-color", "yellow");
        return false;
    } else {
        $("#prescriptionName").parent().css("background-color", "white");
    }

    if (!maxDose.length > 0) {
        $("#maxDose").parent().css("background-color", "yellow");
        return false;
    } else {
        $("#maxDose").parent().css("background-color", "white");
    }

    if (!doseUnit > 0) {
        $("#prescriptionDrugUnit").parent().css("background-color", "yellow");
        return false;
    } else {
        $("#prescriptionDrugUnit").parent().css("background-color", "white");
    }

    if (!startDate > 0) {
        $("#prescriptionStart").parent().css("background-color", "yellow");
        return false;
    } else {
        $("#prescriptionStart").parent().css("background-color", "white");
    }

    if (new Date(startDate) > new Date()) {
        $("#prescriptionStart").parent().css("background-color", "yellow");
        alert("Date in the future");
        return false;
    } else {
        $("#prescriptionStart").parent().css("background-color", "white");
    }

    if (endDate.length > 0) {
        if (new Date(endDate) > new Date()) {
            $("#prescriptionEnd").parent().css("background-color", "yellow");
            alert("End date in the future");
            return false;
        }
        if (new Date(endDate) < new Date(startDate)) {
            $("#prescriptionStart").parent().css("background-color", "yellow");
            $("#prescriptionEnd").parent().css("background-color", "yellow");
            alert("End Date grater then Start Date");
            return false;
        } else {
            $("#prescriptionStart").parent().css("background-color", "white");
            $("#prescriptionEnd").parent().css("background-color", "white");
        }
    }

    if (!multipleTrialId > 0) {
        $("#multipleTrialsList").parent().css("background-color", "yellow");
        return false;
    } else {
        $("#multipleTrialsList").parent().css("background-color", "white");
    }

    if (!reasonStoppedId > 0) {
        $("#reasonStopped").parent().css("background-color", "yellow");
        return false;
    } else {
        $("#reasonStopped").parent().css("background-color", "white");
    }

    if (!responseTypeId > 0) {
        $("#responseType").parent().css("background-color", "yellow");
        return false;
    } else {
        $("#responseType").parent().css("background-color", "white");
    }

    if (!treatmentInducedId > 0) {
        $("#treatmentInduced").parent().css("background-color", "yellow");
        return false;
    } else {
        $("#treatmentInduced").parent().css("background-color", "white");
    }

    return true;
}

function LoadMedicationHistory(data) {
    var htmlStr = "";
    for (var i = 0; i < data.length; i++) {
        var startDate = new Date(data[i].StartDate.substring(6, 19) * 1);
        var endDate = "";

        if (data[i].EndDate != null) {
            var endD = new Date(data[i].EndDate.substring(6, 19) * 1);
            endDate = (endD.getMonth() + 1) + "/" + endD.getDate() + "/" + endD.getFullYear();
        }

        var IsCurrent = "Stopped: " + endDate;
        if (data[i].IsCurrent)
            IsCurrent = "Current";

        htmlStr += "<i>" + data[i].Drug.Name + "</i> <strong>" + data[i].Dosage + "</strong> " + data[i].DosageType;
        htmlStr += " Started on: " + (startDate.getMonth() + 1) + "/" + startDate.getDate() + "/" + startDate.getFullYear() + " - " + IsCurrent;
        htmlStr += "&nbsp;" + data[i].Comments + "";
        htmlStr += "&nbsp;<input type='button' value='Delete' class='buttonGlobalShort deleteSmall' onclick=\"DeleteSubjectsDrug('" + data[i].SubjectDrugId + "'); \">&nbsp;";
        htmlStr += "<br/>";
    }

    $("#medHistorySummary").html(htmlStr);
}

function DeleteSubjectsDrug(id) {
    var ok = confirm("Are you sure you want to delete this medication?");
    if (ok) {
        $.ajax({
            type: "POST",
            url: "/Study/DeleteSubjectsPrescriptionDrug",
            data: "{'subjectDrugId':'" + id + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                //LoadAppointmentMedication(data);
                window.location = window.location;
            },
            error: function (e) {
                alert(e.responseText.substring(11, e.responseText.indexOf("StackTrace") - 2));
            }
        });
    }
}

function DeleteSubjectsSubstance(id) {
    var ok = confirm("Are you sure you want to delete this entry?");
    if (ok) {
        $.ajax({
            type: "POST",
            url: "/Study/DeleteSubjectsSubstance",
            data: "{'substanceId':'" + id + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                window.location = window.location;
                //LoadVisitSubstanceSummary(data);
            },
            error: function (e) {
                alert(e.responseText.substring(11, e.responseText.indexOf("StackTrace") - 2));
            }
        });
    }
}

function GetMedicationChangeHistory(id) {
    var drugId = id;
    var subjectId = $("#subjectId").val();
    $.ajax({
        type: "POST",
        url: "/Study/GetSubjectDrugChangeHistory",
        data: "{'subjectId':'" + subjectId + "','drugId':'" + id + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            ShowDrugChangeHistory(data, id);
        },
        error: function (e) {
            alert(e.responseText.substring(11, e.responseText.indexOf("StackTrace") - 2));
        }
    });
}

function ShowDrugChangeHistory(data, id) {
    $("#history_" + id).html('');
    var history = $("#history_" + id);
    var html = "<span style='text-align:right;width:100%;' ><a href='#' onclick=\"HideHistory('" + id + "');\">X&nbsp;Close</a>&nbsp;</span><br/>";

    for (var i = 0; i < data.length; i++) {
        var started = new Date(data[i].StartDate.substring(6, 19) * 1);
        var changed;
        var ended;
        if (data[i].UpdateDate != null) {
            changed = new Date(data[i].UpdateDate.substring(6, 19) * 1);
        }

        if (data[i].EndDate != null) {
            ended = new Date(data[i].EndDate.substring(6, 19) * 1);
        }

        html += "Dose:" + data[i].Dosage + " " + data[i].DosageType;

        if (i === 0) {
            html += " Started on: " + (started.getMonth() + 1) + "/" + started.getDate() + "/" + started.getFullYear();
        }
        if (changed) {
            html += " Changed on: " + (changed.getMonth() + 1) + "/" + changed.getDate() + "/" + changed.getFullYear();
        }
        if (ended) {
            html += " Stopped on: " + (ended.getMonth() + 1) + "/" + ended.getDate() + "/" + ended.getFullYear();
        }

        html += "&nbsp;&nbsp; " + data[i].Comments + "<br/>";
    }

    if (data.length == 0) {
        html += "NO CHANGES";
    }
    history.append(html);
    history.attr("width", "200px");
    //history.attr("height", "400px");
    history.attr("padding", "10px");
    history.show('slow');
}

function HideHistory(id) {
    $("#history_" + id).html('');
}

function IsNumeric(input) {
    return (input - 0) == input && input.length > 0;
}

function IsDate(input) {
    var date = new Date(input);
    var isDate = date.toString() != "NaN";
    return isDate;
}

function ValidateDates(startDate, endDate) {
    var start = new Date(startDate);
    var end = new Date();
    var today = new Date();

    if (start > today) {
        alert("Start Date in the future");
        return false;
    }

    if (endDate.length > 0) {
        end = new Date(endDate);
        if (end > today) {
            alert("End Date in the future");
            return false;
        }

        if (end < start) {
            alert("Start date grater then End date");
            return false;
        }
    }
    return true;
}